# -*- coding: utf-8 -*-
import logging
import os
import sys
import time
import traceback

import requests
from bs4 import BeautifulSoup
from lxml import etree

# add up one level dir into sys path

sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.lottery.handler import crawl_from_opencai
from common.lottery.cyclical.bj_pk10.db.activity import fullfill_result
from common.lottery import LOTTERY_TYPE, OPENCAI_LOTTERY_TYPES
from common.timer import TIMER_EVENT_TYPE, TimerEvent
from common.utils import tz

# 500彩票网

URL_168 = 'http://api.1680210.com/pks/getLotteryPksInfo.do?lotCode=10001'

URL = 'http://kaijiang.500.com/static/info/kaijiang/xml/bjpkshi/%s.xml'


def _internal_fill_168(phase, number, refer):
    number = ','.join([str(int(each)) for each in number.split(',')])
    activity = fullfill_result(phase, number, refer)
    if activity:
        TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {  # 走勢圖
            'number': number, 'term': phase,
            'activity_type': LOTTERY_TYPE.BJ_PK10}, tz.now_ts()
                          )
        TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {  # 中獎結算
            'number': number, 'term': phase,
            'activity_type': LOTTERY_TYPE.BJ_PK10}, tz.now_ts())


def _parse_and_fill_168(data, refer):
    if data['errorCode'] == 0:
        data = data['result']['data']
        if isinstance(data, dict):
            phase = data['preDrawIssue']  # 期號
            number = data['preDrawCode']  # 開獎結果
            _internal_fill_168(phase, number, refer)
        elif isinstance(data, list):
            for d in data:
                phase = d['preDrawIssue']  # 期號
                number = d['preDrawCode']  # 開獎結果
                _internal_fill_168(phase, number, refer)


def crawl_from_168(date=None):
    url = 'http://api.1680210.com/pks/getLotteryPksInfo.do?lotCode=10001'
    try:
        response = requests.get(url, timeout=10)
    except Exception as e:
        print traceback.print_exc()
    if response.status_code != 200:
        raise RuntimeError('request error')
    _parse_and_fill_168(response.json(), url)


def _parse_and_fill_official(resp, refer):
    soup = BeautifulSoup(resp, 'lxml')
    trs = soup.select('div.lott_cont tr')
    for tr in trs[1:]:
        tds = tr.select('td')
        phase = tds[0].text.strip()
        number = tds[1].text.strip()
        number = ','.join([str(int(each)) for each in number.split(',')])
        activity = fullfill_result(phase, number, refer)
        if activity:
            TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {
                'number': number, 'term': phase,
                'activity_type': LOTTERY_TYPE.BJ_PK10}, tz.now_ts())
            TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {
                'number': number, 'term': phase,
                'activity_type': LOTTERY_TYPE.BJ_PK10}, tz.now_ts())


def _parse_and_fill(resp, refer):
    nodes = etree.fromstring(resp)
    for node in nodes:
        attrib = node.attrib
        phase = attrib['expect']  # 期号和日期无关
        number = attrib['opencode']
        number = ','.join([str(int(n)) for n in number.split(',')])
        activity = fullfill_result(phase, number, refer)
        if activity:
            TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {
                'number': number, 'term': phase,
                'activity_type': LOTTERY_TYPE.BJ_PK10}, tz.now_ts())
            TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {
                'number': number, 'term': phase,
                'activity_type': LOTTERY_TYPE.BJ_PK10}, tz.now_ts())


def crawl_history(date):
    url = URL % date.strftime('%Y%m%d')
    try:
        response = requests.get(url, timeout=10)
    except Exception as e:
        raise
    if response.status_code != 200:
        raise RuntimeError('request error')
    _parse_and_fill(response.content, url)
    # crawler from 168
    url = 'https://api.api68.com/pks/getPksHistoryList.do?date={}&lotCode=10001'.format(
        date.strftime('%Y-%m-%d')
    )
    try:
        response = requests.get(url, timeout=10)
    except Exception as e:
        print traceback.print_exc()
    if response.status_code != 200:
        raise RuntimeError('request error')
    _parse_and_fill_168(response.json(), url)


''' 在cron里面每天北京时间凌晨1点跑头一天
'''


def crawl_newest(now=None):
    now = now or tz.local_now()
    refer = URL % now.strftime('%Y%m%d')
    url = refer
    try:
        response = requests.get(url, timeout=10)
    except Exception:
        return now
    if response.status_code != 200:
        return now
    _parse_and_fill(response.content, refer)
    return None


def main(d):
    while True:
        try:
            crawl_from_opencai(LOTTERY_TYPE.BJ_PK10)
        except Exception as e:
            logging.exception(u'%s error: %s' % (OPENCAI_LOTTERY_TYPES.get(LOTTERY_TYPE.BJ_PK10), e))
        if d:
            break
        time.sleep(60)


if __name__ == '__main__':
    date = sys.argv[1] if len(sys.argv) > 1 else None
    main(date)

